//
//  TipCalculatorViewController.m
//  TipCalculator
//
//  Created by Fox School of Business MIS on 9/18/09.
//  Copyright __MyCompanyName__ 2009. All rights reserved.
//

#import "TipCalculatorViewController.h"

@implementation TipCalculatorViewController

@synthesize buttonCalculateTip;
@synthesize buttonTipDialog;
@synthesize buttonPlayVideo;
@synthesize textTipPercent;
@synthesize textCheckAmount;
@synthesize labelTipAmount;
@synthesize textDialogTipPercent;

/* Calculates the total tip amount, result is stored labelTipAmount
   labeltipAmount = textCheckAmount * textTipPerecent */
-(IBAction) buttonCalculateTipTouched {

	/* Calculate the tip */
	double amt = [textCheckAmount.text doubleValue];
	double tip = [textTipPercent.text doubleValue];
	double tipTotal = amt * tip/100;
	
	labelTipAmount.text = [NSString stringWithFormat: @"$%.2f", tipTotal]; //truncates display to two decimal points; no rounding is done.
}

/* Display a dialog containing a textbox for the user to input the tip percentage */
-(IBAction) buttonTipDialogTouched {
	
	UIAlertView* dialog = [[[UIAlertView alloc] init] autorelease];

	[dialog setDelegate: self];	
	[dialog setTitle: @"Enter Tip Percentage"];
	/* Add and ok/cancel button to alert view.  Buttons are added "manually" so everything is positioned correctly.  Not the right way to do this.
	 *
	 * Correct way should be to subclass UIAlertView ... ?
	 */
	UIButton* buttonOk = [UIButton buttonWithType: UIButtonTypeRoundedRect]; //hack -- these are never freed, as doing so causes a crash.
	UIButton* buttonCancel = [UIButton buttonWithType: UIButtonTypeRoundedRect]; //hack -- these are never freed, as doing so causes a crash.
	
	[buttonOk setTitle: @"OK" forState: UIControlStateNormal];
	[buttonCancel setTitle: @"Cancel" forState: UIControlStateNormal];
	
	buttonOk.frame = CGRectMake(60, 100, 70, 40);
	buttonCancel.frame = CGRectMake(140, 100, 70, 40);
	
	[buttonOk addTarget: self action: @selector(dialogOkButtonTouched:) forControlEvents:UIControlEventTouchUpInside];
	[buttonCancel addTarget: self action: @selector(dialogCancelButtonTouched:) forControlEvents: UIControlEventTouchUpInside];
	
	[dialog addSubview: buttonOk];
	[dialog addSubview: buttonCancel];
	
	/* Create a textfield control and add it to the dialog view */
	textDialogTipPercent = [[[UITextField alloc] initWithFrame: CGRectMake(20, 55, 245, 25)] autorelease];
	[textDialogTipPercent setBackgroundColor: [UIColor whiteColor]];
	[textDialogTipPercent setKeyboardType: UIKeyboardTypeNumberPad];
	[dialog addSubview: textDialogTipPercent];
	textDialogTipPercent.text = textTipPercent.text;  //set the text field to hold the percentage from main tip calculator view
	
	/* Show dialog and release resources */
	CGAffineTransform moveUp = CGAffineTransformMakeTranslation(0, 240);
	[dialog setTransform: moveUp];
	[dialog show]; //control continues on from here depsite the view still being shown.  if controls are made autorelease, they're freed still even if the dialog is closed... ?
}

/* Called prior to the tip dialog being displayed.  Resizes the dialog so the added textfield will fit properly. */
- (void) willPresentAlertView:(UIAlertView*) view {
	
	view.frame = CGRectMake(20, 300, 300, 200);
}

- (void) dialogOkButtonTouched: (id) sender {

	textTipPercent.text = textDialogTipPercent.text;
	UIAlertView* alertview = (UIAlertView*)[sender superview]; //get alertview object, so we can close it
	[alertview dismissWithClickedButtonIndex:0 animated:YES];
}

- (void) dialogCancelButtonTouched: (id) sender {
	
	UIAlertView* alertview = (UIAlertView*)[sender superview]; //get alertview object, so we can close it
	[alertview dismissWithClickedButtonIndex:0 animated:YES];
}

/* Called when a button is selected in the tip dialog box, we don't actually do anything though. */
- (void) alertView:(UIAlertView*)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
	
}

/* Add in an implied decimal point, since the number pad does not have one. */ 			
- (IBAction) textCheckAmountChanged {

	static BOOL firedFromMethod = NO;
	if(firedFromMethod == YES) /* then return so we don't end up modifying the textCheckAmount.text, causing this method to be called over and over recursively. */
	{
		firedFromMethod = NO;
		return;
	}
	
	/* Remove any decimal points already present */
	NSMutableString* checkAmount = [[NSMutableString alloc] initWithString: [textCheckAmount.text stringByReplacingOccurrencesOfString: @"." withString: @""]];
	

	/* remove any preexisting leading zeroes */
	int firstNonLeadingZero = 0;
	for(int x = 0; x < [checkAmount length]; ++x)
	{
		char c = [checkAmount characterAtIndex:x];
		if(c != '0' && c != '.')
		{
			firstNonLeadingZero = x;
			break;
		}
		
	}
	checkAmount = [[NSMutableString alloc] initWithString: [checkAmount substringFromIndex: firstNonLeadingZero]]; 
	
	if([checkAmount length] < 3) //then we need to add in necessary leading zeroes
	{
		int leadingZeroCount = 3 - [checkAmount length] ; /* number of leading zeroes to add into string */
	
		for(int x = 0; x < leadingZeroCount; ++x) /* add in leading zeroes */
			[checkAmount insertString: @"0" atIndex: 0];
	}

	/* Add in the deicmal point to string */
	int decimalIndex = [checkAmount length] - 2; /* index of decimal point: two characters from the left of the string */
	[checkAmount insertString: @"." atIndex: decimalIndex];

	firedFromMethod = YES; /* the next line will cause an "Editting Changed" event to be fired, so let this method know it was us who did it to prevent recursion */
	textCheckAmount.text = checkAmount;

	[checkAmount release];
}

/* Switches to the movie view */
- (IBAction) buttonPlayVideoTouched {
	/* Create and run an animation for switching the view.  Set self as an animation delegate.  When the animation
	 is done running, switch the subview of the main window to the tipcalculator view */
	

	[UIView beginAnimations:@"change to view to movie" context:nil];
	[UIView setAnimationDelegate: self];
	[UIView setAnimationDuration: .55];
	[UIView setAnimationCurve: UIViewAnimationCurveLinear];
	[UIView setAnimationTransition: UIViewAnimationTransitionCurlDown forView: self.view.window cache:YES];

	UIWindow* window = self.view.window;
	[self.view removeFromSuperview];
	[movieViewController setTipCalculatorView: self.view];
	[window addSubview: movieViewController.view];
	[UIView commitAnimations];

}

/* Called when the "change view to movie" animation is done.  Tells the movieControllView to paly the movie */
- (void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
	[movieViewController playMovie];
}
- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidLoad {
	movieViewController = [[MovieViewController alloc] init];
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}

@end
